package com.zyz.forum.file;


import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.zyz.forum.common.AppResult;
import com.zyz.forum.common.ResultCode;
import com.zyz.forum.dao.UserMapper;
import com.zyz.forum.exception.ApplicationException;
import com.zyz.forum.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Slf4j
@Service
public class OSSService {

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS ossClient;

    @Autowired
    private UserMapper userMapper;


    public OSSResult uploadFile(MultipartFile file, User user) throws Exception {
        InputStream inputStream = null;
        try {
            String fileName;
            if (file.getOriginalFilename() != null) {
                fileName = file.getOriginalFilename().toLowerCase();
            } else {
                fileName = "default.png"; // 如果拿不到文件名，那就按照default.png命名处理
            }
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
//            log.error("======== extName:{}",extName); //jpg
            inputStream = file.getInputStream();
            return upload(extName, inputStream,user);
        } catch (Exception e) {
            log.error("OSS upload file error", e);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    // 上传文件
    private OSSResult upload(String fileType, InputStream inputStream,User user) {
        // key pattern: file/id.xxx, cannot start with /
        String endName = ObjectId.next() + "." + fileType;
        log.error("=====endName:{}",endName);
        user.setAvatarUrl(endName);
        int row = userMapper.updateByPrimaryKey(user);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        String key = prop.getPathPrefix() + endName; // 生成的文件名字
        log.info("-----------key------------{}",key);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
        PutObjectRequest request = new PutObjectRequest(prop.getBucketName(), key, inputStream, objectMetadata);
        PutObjectResult putObjectResult;
        try {
            putObjectResult = ossClient.putObject(request);// 对象值得就是图片（文件）
        } catch (Exception e) {
            log.error("OSS put object error: {}", ExceptionUtil.stacktraceToOneLineString(e, 500));
            throw new ServiceException("文件上传失败.");
        }
        return assembleOSSResult(key, putObjectResult);
    }

    // 封装返回对象
    private OSSResult assembleOSSResult(String key, PutObjectResult putObjectResult) {
        OSSResult ossResult = new OSSResult();
        if (putObjectResult == null || StrUtil.isBlank(putObjectResult.getRequestId())) {
            ossResult.setSuccess(false);
        } else {
            ossResult.setSuccess(true);
            ossResult.setName(FileUtil.getName(key));
        }
        return ossResult;
    }
}
